<?php
/*
 * @Author: lokei
 * @Date: 2022-08-02 21:19:38
 * @LastEditors: lokei
 * @LastEditTime: 2022-08-15 21:51:33
 * @Description: 
 */

namespace App\Http\Controllers\Auth;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Models\Ucenter\AdministratorModel;
use App\Models\Ucenter\UserModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;

class AdminController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    //

    public function login(Request $request)
    {
        $user = UserModel::where('username', '=', $request->input('username'))->first();
        if (is_null($user)) {
            $res = ResultTool::fail();
            $res['errorCode'] = 1000;
            $res['errorMsg'] = '用户不存在！';
            return $res;
        }
        $password = sha1($request->input('password') . '-' . $user->salt . '-' . env('AUTH_KEY'));
        if ($user->password != $password) {
            $res = ResultTool::fail();
            $res['errorCode'] = 1001;
            $res['errorMsg'] = '密码错误！';
            return $res;
        }
        $res = ResultTool::success();
        $token = Auth::login($user);
        $res['data']['token'] = $token;
        return $res;
    }

    public function info(Request $request)
    {
        $token = $request->input('token');
        $user = JWTAuth::setToken($token)->authenticate();
        $roles = [];
        if (!is_null($user)) {
            $administrator = AdministratorModel::where('uid', '=', $user->uid)->first();
            if (!is_null($administrator)) {
                array_push($roles, $administrator->role);
            }
        }
        $res = ResultTool::success();
        $res['data']['roles'] = $roles;
        return $res;
    }

}
